package com.rykj.energy.common.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {


    public final static String CAMERA_IMG_PATH = "faceImg" + File.separator + "cameraImg" + File.separator;

    /**
     * 将图片转成二进制数组
     * @return
     */
    public static byte[] getImageBinary(String filePath){
        File f = new File(filePath);
        BufferedImage bi;
        String[] split = filePath.split("\\.");

        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, split[split.length-1], baos);
            byte[] bytes = baos.toByteArray();

            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写文件
     *
     * @param f
     * @param content
     */
    public static void writeFile(File f, String content) {
        writeFile(f, content, "utf-8");
    }

    /**
     * 写文件
     *
     * @param f
     * @param content
     */
    public static void writeFile(File f, String content, String encode) {
        try {
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f), encode);
            BufferedWriter utput = new BufferedWriter(osw);
            utput.write(content);
            utput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写文件
     *
     * @param path
     * @param content
     */
    public static void writeFile(String path, String content, String encode) {
        File f = new File(path);
        writeFile(f, content, encode);
    }

    /**
     * 写文件
     *
     * @param path
     * @param content
     */
    public static void writeFile(String path, String content) {
        File f = new File(path);
        writeFile(f, content, "utf-8");
    }

    /**
     * 读取文件
     *
     * @param file
     * @return
     */
    public static String readFile(File file) {
        return readFile(file, "UTF-8");
    }

    /**
     * 读取文件
     *
     * @param file
     * @return
     */
    public static String readFile(File file, String encode) {
        String output = "";

        if (file.exists()) {
            if (file.isFile()) {
            	BufferedReader input = null;
                try {
                    InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encode);
                    input = new BufferedReader(isr);
                    StringBuffer buffer = new StringBuffer();
                    String text;
                    while ((text = input.readLine()) != null) {
                        buffer.append(text + "\n");
                    }
                    output = buffer.toString();

                } catch (IOException ioException) {
                    System.err.println("File Error！");
                } finally {
                	if (input != null) {
                		try {
							input.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
                	}
                }
            } else if (file.isDirectory()) {
                String[] dir = file.list();
                output += "Directory contents：\n";
                for (int i = 0; i < dir.length; i++) {
                    output += dir[i] + "\n";
                }
            }

        } else {
            System.err.println("Does not exist！");
        }

        return output;
    }

    /**
     * 读取文件
     *
     * @param fileName
     * @return
     */
    public static String readFile(String fileName, String encode) {
        File file = new File(fileName);
        return readFile(file, encode);
    }

    /**
     * 读取文件
     *
     * @param fileName
     * @return
     */
    public static String readFile(String fileName) {
        return readFile(fileName, "utf-8");
    }


    /**
     * 获取目录下所有文件
     *
     * @param folder
     * @return
     */
    public static List<File> getFiles(String folder) {
        File file = new File(folder);
        List<File> files = new ArrayList<File>();
        if (file.exists()) {
            File[] sonFiles = file.listFiles();
            if (sonFiles != null && sonFiles.length > 0) {
                for (int i = 0; i < sonFiles.length; i++) {
                    if (!sonFiles[i].isDirectory()) {
                        files.add(sonFiles[i]);
                    }
                }
            }
        }
        return files;
    }

    /**
     * 递归查看路径下文件,返回文件路径
     * @param fileName 搜索的文件名
     * @param folder 指定搜索路径
     * @return
     */
    static String filePath = "";
    public static String findFile(String fileName, String folder){
        File file = new File(folder);
        if (file.exists()) {
            File[] sonFiles = file.listFiles();
            if (sonFiles != null && sonFiles.length > 0) {
                for (int i = 0; i < sonFiles.length; i++) {
                    File file1 = sonFiles[i];
                    if (!sonFiles[i].isDirectory()) {
                        if(file1.getName().equals(fileName)){
                            filePath = file1.getParent();
                            break;
                        }
                    }else{
                        findFile(fileName,file1.getPath());
                    }
                }
            }
        }
        return filePath;
    }
    /**
     * 获取目录下所有文件夹
     *
     * @param folder
     * @return
     */
    public static List<File> getFolders(String folder) {
        File file = new File(folder);
        List<File> files = new ArrayList<File>();
        if (file.exists()) {
            File[] sonFiles = file.listFiles();
            if (sonFiles != null && sonFiles.length > 0) {
                for (int i = 0; i < sonFiles.length; i++) {
                    if (sonFiles[i].isDirectory()) {
                        files.add(sonFiles[i]);
                    }
                }
            }
        }
        return files;
    }

    /**
     * 判断是否有子目录
     *
     * @param folder
     * @return
     */
    public static boolean hasSonFolder(String folder) {
        File file = new File(folder);
        return hasSonFolder(file);
    }

    /**
     * 判断是否有子目录
     *
     * @return
     */
    public static boolean hasSonFolder(File file) {
        if (file.exists()) {
            File[] sonFiles = file.listFiles();
            if (sonFiles != null && sonFiles.length > 0) {
                for (int i = 0; i < sonFiles.length; i++) {
                    if (sonFiles[i].isDirectory()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 创建目录
     *
     * @param folder
     */
    public static void mkdir(String folder) {
        File file = new File(folder);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 复制文件
     *
     * @param src
     * @param dst
     */
    public static void copy(File src, File dst) {
        try {
			int bufferize = 32 * 1024;
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(src);
                out = new FileOutputStream(dst);
                byte[] buffer = new byte[bufferize];
                int count;
                while ((count = in.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制文件夹
     *
     * @param sourceDir
     * @param targetDir
     * @throws IOException
     */
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        if (new File(sourceDir).exists()) {
            // 新建目标目录
            File targetFolder = new File(targetDir);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
            // 获取源文件夹当前下的文件或目录
            File[] file = (new File(sourceDir)).listFiles();
            for (int i = 0; i < file.length; i++) {
                if (file[i].isFile()) {
                    // 源文件
                    File sourceFile = file[i];
                    // 目标文件
                    File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                    copy(sourceFile, targetFile);
                }
                if (file[i].isDirectory()) {
                    // 准备复制的源文件夹
                    String dir1 = sourceDir + "/" + file[i].getName();
                    // 准备复制的目标文件夹
                    String dir2 = targetDir + "/" + file[i].getName();
                    copyDirectiory(dir1, dir2);
                }
            }
        }
    }

    /**
     * 获取扩展名
     */
    public static String getExt(File src) {
        if (src != null) {
            String name = src.getName();
            return name.substring(name.lastIndexOf("."), name.length());
        }
        return "";
    }

    /**
     * 获取扩展名
     */
    public static String getExt(String src) {
        if (src != null) {
            return src.substring(src.lastIndexOf("."), src.length());
        }
        return "";
    }

    /**
     * 删除指定文件
     *
     * @param path
     */
    public static void del(String path) {
        File file = new File(path);
        deleteFile(file);
    }

    /**
     * 递归删除文件夹下所有文件
     *
     * @param file
     */
    public static void deleteFile(File file) {
    	//判断文件是否存在
        if (file.exists()) {
        	//判断是否是文件
            if (file.isFile()) {
            	//delete()方法 你应该知道 是删除的意思;
                file.delete(); 
              //否则如果它是一个目录
            } else if (file.isDirectory()) { 
            	//声明目录下所有的文件 files[];
                File[] files = file.listFiles();
              //遍历目录下所有的文件
                for (int i = 0; i < files.length; i++) {
                	//把每个文件 用这个方法进行迭代
                    deleteFile(files[i]); 
                }
            }
            file.delete();
        }
    }

    public static File createTempFile(String fileName, byte[] contents)throws Exception {
        File convFile = new File(fileName);
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(contents);
        fos.close();
        return convFile;
    }
    
    public static String write2File(String fileName, String data){
        OutputStreamWriter osw = null;
        File f = new File(fileName);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        String path = null;
        OutputStream out = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(f);
            osw = new OutputStreamWriter(out, "utf-8");
            bw = new BufferedWriter(osw);
            bw.write(data);
            bw.flush();
            path = f.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bw !=null){
                try {
                	bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return path;
    }

    public static void writeFile(FileInputStream fileInputStream, String filePath){
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(bos != null){
                try{
                    bos.flush();
                    bos.close();
                }catch (Exception e1){
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
//        List<File> list = getFiles("G:\\rykj-behavior-server\\bin\\out");
//        for(File f : list){
//            System.out.println(f.getName());
//        }
//        System.out.println(findFile("student-info.xlsx","D:\\opt\\var"));
//        getImageBinary("D:\\测试库02正\\表情\\奥迪男\\奥迪男 5.png");
    }
}
